package com.allen.app.config;

import com.allen.app.common.config.rabbitmq.DefaultRabbitInitializer;
import com.allen.app.common.config.rabbitmq.RabbitInitializer;
import com.allen.app.zdemo.domain.DelayExchange;
import com.allen.app.zdemo.domain.NormalExchange;
import com.allen.app.zdemo.domain.PublishExchange;
import java.util.stream.Stream;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@AllArgsConstructor
@Slf4j
public class AppServerConfig {

    /**
     * 初始化mq信息
     */
    @Bean
    @ConditionalOnProperty(name = {"spring.rabbitmq.host"})
    public RabbitInitializer rabbitInitializer() {
        return new DefaultRabbitInitializer();
    }

    @Bean
    @ConditionalOnBean(RabbitInitializer.class)
    public Object init(RabbitInitializer initializer) {
        log.info("\t===>>\t[AppServerConfig] init initializing......");
        //普通队列初始化
        Stream.of(NormalExchange.values())
            .forEach(normal -> initializer.normal(normal.getExchangeName(), normal.getQueueName()));

        //事件初始化
        Stream.of(PublishExchange.values()).forEach(publish -> Stream.of(publish.getQueues()).forEach(queue -> {
            initializer.publish(publish.getName(), queue.getName());
        }));

        //延迟队列初始化
        Stream.of(DelayExchange.values()).forEach(delay -> Stream.of(delay.getQueues()).forEach(queue -> {
            if (delay.isPlugsDelay()) {
                initializer.delayDifferentTime(delay.getExchangeName(), queue.getForwardName());
            } else {
                initializer.delay(delay.getExchangeName(), queue.getDelayName(), queue.getForwardName());
            }
        }));
        return new Object();
    }
}
